package com.lemon.bean.stageBean;

import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.apache.commons.io.FileUtils;

import java.io.IOException;
import java.net.URL;
import java.util.Set;

import static com.lemon.beanManager.BeanContainer.beanFactory;

public class LoadDelete {
    private Stage stage = new Stage();
    private Pane deleteConfirmWindow;

    public Text title;
    public Button confirm;
    public Button cancel;
    private boolean isConfirm;

    public void loadDelete() {
        try {
            deleteConfirmWindow = FXMLLoader.load(getClass().getResource("deleteConfirm.fxml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        title = (Text) beanFactory.getBean("deleteStageTitle");
        confirm = (Button) beanFactory.getBean("deleteStageConfirm");
        cancel = (Button) beanFactory.getBean("deleteStageCancel");
        Scene scene = new Scene(deleteConfirmWindow, 320, 150);
        stage.setScene(scene);
        stage.setWidth(320);
        stage.setHeight(150);
        stage.initStyle(StageStyle.UNDECORATED);

        URL resource = this.getClass().getResource("css/deleteConfirm.css");
        addStyle(resource.toExternalForm());
    }

    public void initFunction() {
        confirm.setOnAction(e -> {
            deleteImage();
            close();
        });
        cancel.setOnAction(e -> {
            isConfirm = false;
            close();
        });
    }

    public void show() {
        stage.show();
    }

    public void close() {
        beanFactory.remove("deleteStageTitle");
        beanFactory.remove("deleteStageConfirm");
        beanFactory.remove("deleteStageCancel");
        stage.close();
    }

    public void setTitle(String title) {
        this.title.setText(title);
    }

    public boolean confirm() {
        return this.isConfirm;
    }

    private FlowPane fp;

    public void setFlowPane(FlowPane fp) {
        this.fp = fp;
    }

    public void deleteImage() {
        Set<Node> nodes = fp.lookupAll("ImageView");
        for (Node node : nodes) {
            if (node.getParent().getParent().getParent().getOpacity() == 0.95) {
                ImageView iv = (ImageView) node;
                fp.getChildren().remove(node.getParent().getParent().getParent());
                String str = iv.getImage().getUrl().replaceAll("file:", "");
                iv.setImage(null);
                System.gc();
                FileUtils.fileDelete(str);
            }
        }
    }
    public void addStyle(String cssPath){
        deleteConfirmWindow.getStylesheets().add(cssPath);
    }
}
